package com.smasher.domain.helper

import com.smasher.domain.entity.BeanDomain
import com.tencent.mmkv.MMKV

/**
 * @author HXZ_Android
 */
class DomainHelper private constructor() {

    private val mmkv = MMKV.mmkvWithID(MMKV_ID)

    private object SingletonHolder {
        val holder = DomainHelper()
    }

    fun init(scheme: String, host: String, port: Int) {
        val time = System.currentTimeMillis()
        val id = (time % 10000).toInt()
        val domain = BeanDomain(
            id = id,
            name = time.toString(),
            scheme = scheme,
            host = host,
            port = port
        )
        if (currentDomain == null) {
            currentDomain = domain
        }
    }

    var currentDomain: BeanDomain?
        get() {
            val scheme = mmkv.decodeString(DOMAIN_SCHEME)
            val host = mmkv.decodeString(DOMAIN_HOST)
            val port = mmkv.decodeInt(DOMAIN_PORT)

            if (scheme == null || host == null) {
                return null
            }

            val time = System.currentTimeMillis()
            val id = (time % 10000).toInt()
            return BeanDomain(
                id = id,
                name = time.toString(),
                scheme = scheme,
                host = host,
                port = port
            )
        }
        set(domain) {
            if (domain != null) {
                mmkv.encode(DOMAIN_SCHEME, domain.scheme)
                mmkv.encode(DOMAIN_HOST, domain.host)
                mmkv.encode(DOMAIN_PORT, domain.port)
            }
        }

    companion object {
        const val TAG: String = "DomainHelper"
        const val MMKV_ID: String = "domain_setting"
        const val DOMAIN_SCHEME: String = "domain_scheme"
        const val DOMAIN_HOST: String = "domain_host"
        const val DOMAIN_PORT: String = "domain_port"

        @JvmStatic
        fun getInstance(): DomainHelper {
            return SingletonHolder.holder
        }

    }

}